
/**
 * 过度页+登录页
 */

import React, { Component } from 'react'
import {
  StyleSheet,
  Animated,
	Text,
	View,
	Image,
	TouchableWithoutFeedback,
	TextInput,
	StatusBar,
	ScrollView
} from 'react-native'
import Screen from './src/common/screen'
import FetchResources from './src/common/FetchResources'
import GetSetStorge from './src/common/GetSetStorge'
import { RouteHelper } from 'react-navigation-easy-helper'
import NavPage from './src/common/NavPage'
import SegmentedView from 'teaset/components/SegmentedView/SegmentedView'
import Btn from './src/common/Btn'
import axios from 'axios'
import qs from 'qs'
import Toast from 'antd-mobile/lib/toast'

const splashImg = require('./src/img/splashImg.png')//加载图片
export default class Splash extends Component {
  constructor(props) {
    super(props);
		this.state = {
			sellerId: '',
			password: '',
			dynamicCode: '',
			activeIndex: 0,
			countdown: 60,
			isDown: false,
			now: +new Date(),
      imgCode: '',
      bounceValue: new Animated.Value(1),
			showLogin:false,
			valueB:0,
			permissionList:[]
		}
		GetSetStorge.setStorgeAsync('token', '')
   
  }

  componentDidMount() {
    Animated.timing(
      this.state.bounceValue, { toValue: 1.08, duration: 3000 }
    ).start()

    this.timer = setTimeout(() => {
      
      GetSetStorge.getStorgeAsync('isFrist').then((result) => {
        if (result) {
					GetSetStorge.getStorgeAsync('sessionId').then((result) => {
						if (result) {
							RouteHelper.navigate('App',{pageType:'sellTicket'})
							this.setState({showLogin:false})
						} else {
							this.setState({showLogin:true})
						}
					}).catch((error) => {
						console.log('==========================')
						console.log('系统异常' + error)
						console.log('==========================')
					})
        } else {
					this.setState({showLogin:true})
          GetSetStorge.setStorgeAsync('isFrist', 'true')
        }
        
      }).catch((error) => {
        console.log('==========================')
        console.log('系统异常' + error)
        console.log('==========================')
			})

    }, 3000)

  }

  doLogin() {
		let { sellerId, password, dynamicCode, activeIndex } = this.state
		this.setState({
			valueB:10
		})
		if (sellerId == '') {
			Toast.info('请输入账号！', 0.5)
			return
		}

		if (password == '') {
			Toast.fail('请填写密码', 0.5)
			return
		}
		Toast.loading('登录中...', 0)
		
		axios.post(FetchResources.Fetch.Login,//登录
			qs.stringify({
				sellerId,
				password
			})
		).then((response) => {
			Toast.hide()
			if(response.data.success){//登录成功
				let userId = response.data.data.user.sellerId
				this.setState({ 
					permissionList:response.data.data.permissionList
				},()=>{
					GetSetStorge.setStorgeAsync('sessionId', response.data.sessionId || '')
					GetSetStorge.setStorgeAsync('loginInfo', `${userId}|${password}` || '')
					RouteHelper.navigate('App',{pageType:'sellTicket'})
				})
			}else{
				Toast.fail(response.data.errorMessage, 0.5)
			}
		}).catch((error) => {
      Toast.hide()
    })
  }
  
  componentWillUpdate = () => {
    clearTimeout(this.timer)
  }

  render() {
		let { countdown, isDown, now, sellerId,password } = this.state
		let { showLogin } = this.props.navigation.state.params || ''
    return (
			<ScrollView 
							showsVerticalScrollIndicator={false}    // 隐藏垂直指示器
							style={{ flex: 1, }}
						>
      <View style={{flex:1}}>
				<StatusBar
					animated={true}
					hidden={false}
					backgroundColor={'transparent'}
					translucent={true}
					barStyle={'default'}
					showHideTransition={'fade'}
					networkActivityIndicatorVisible={true}
				/>
        {
          this.state.showLogin || showLogin ? 
          <View style={styles.container}>
            <View>
							<Image  source={require('./src/img/loginBg.png')} style={{height:Screen.height,width:Screen.width}} />
							<Image  source={require('./src/img/logo.png')} style={{position:'absolute',top:100,left:75.5,height:85,width:220}} />
					
						</View>
              
            <View style={styles.layout}>
              <View style={[styles.lines, styles.accounts]}>
								<Image  source={require('./src/img/user.png')} style={{height:27,width:27}} />
                <TextInput
                  placeholder="用户名"
                  underlineColorAndroid="transparent"
                  keyboardType={'numeric'}
                  returnKeyType={'next'}
                  onSubmitEditing={() => this.refs.password.focus()}
                  maxLength={11}
                  placeholderTextColor='#ccc'
                  style={styles.txt}
                  value={sellerId}
                  onChangeText={(sellerId) => this.setState({ sellerId })}
                />
              </View>
              <View style={[styles.lines, styles.pwd]}>
								<Image  source={require('./src/img/lock.png')} style={{height:27,width:27}} />
                <TextInput placeholder="密码"
                  underlineColorAndroid="transparent"
                  ref={'password'}
                  returnKeyType={'send'}
                  onSubmitEditing={this.doLogin.bind(this)}
                  placeholderTextColor='#ccc'
                  secureTextEntry={true}
                  style={styles.txt}
                  onChangeText={(password) => { this.setState({ password }) }}
                />
              </View>
							<TouchableWithoutFeedback activeOpacity={1} onPress={this.doLogin.bind(this)}  >
								<View style={{marginTop:64}} >
									<Image  source={require('./src/img/login.png')} style={{height:80,width:298,marginBottom:this.state.valueB}}  />
								</View>
							</TouchableWithoutFeedback>
							
            </View>

            
					</View> : 
					<View>
          <Animated.Image
            style={{
              width: Screen.width,
              height: Screen.height,
              transform: [{ scale: this.state.bounceValue }]
            }}
            source={splashImg}
          />

						<Image  source={require('./src/img/logo.png')} style={{position:'absolute',bottom:100,left:65.5,height:95,width:240}} />
					</View>
        }

      </View>
			</ScrollView>
    )
  }
}

const styles = StyleSheet.create({
	container: {
    flex: 1,
    flexDirection:'column',
		backgroundColor: '#F6F7F8'
	},
	layout: {
		// flex: 1,
		alignItems: 'center',
		justifyContent: 'center',
		paddingLeft: 20,
		paddingRight: 20,
		position:'absolute',
		bottom:70,
		width:Screen.width,
		height:Screen.height*0.35,
		// left:Screen.width*0.15,
		// backgroundColor:'#f00'
    // marginTop:100
	},
	txt: {
		height: 40,
		padding: 0,
		paddingLeft: 8,
		fontSize: 15,
		// marginBottom:20
		flex: 1,
	},
	lines: {
		flexDirection: 'row',
		alignItems: 'center',
		height: 42,
		// width:Screen.width*0.7,
		width:241,
		borderColor:'#D0D8DE',
		borderWidth:1,
		borderStyle:'solid',
		borderRadius:25,
		backgroundColor:'#fff',
		paddingHorizontal:10,
		marginBottom:10
	},
	accounts: {
		marginTop: 30
	},
	pwd: {
		marginTop: 10
	},

	forgot: {
		justifyContent: 'flex-end',
    paddingHorizontal: 20,
	},
	login: {
		marginTop: Screen.height * 0.15
	},
	view: {
		backgroundColor: '#105eae',
		borderRadius: 5
	},
	textBtn: {
		textAlign: 'center',
		fontSize: 20,
		lineHeight: 50,
		height: 50,
		color: "white"
	},
	fontSize17: {
		fontSize: 16,
		width: 60
	},
	fontSize15: {
		fontSize: 15
	},
	color: {
		color: '#105eae'
	}
})